package com.example.demo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.QueryPageParam;
import com.example.demo.common.Result;
import com.example.demo.entity.Menu;
import com.example.demo.entity.User;
import com.example.demo.service.IMenuService;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-01-21
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;

    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginRequest){

        String no = loginRequest.get("no");
        String password = loginRequest.get("password");
        User user = userService.lambdaQuery().eq(User::getNo, no).one();

        List<Menu> menuList = menuService.lambdaQuery()
                .like(Menu::getMenuright, user.getRoleId().toString())
                .list();
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        data.put("menu", menuList);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        if (password.equals(user.getPassword())) {
            // 自定义会话逻辑（如存入Session或Token）
            return Result.suc(data);
        } else {
            return Result.fail("密码错误");
        }
    }
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 可选：清除会话（如果使用Session）
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return Result.suc("登出成功");
    }

    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no){
        List list = userService.lambdaQuery().eq(User::getNo,no).list();
        return list.size()>0?Result.suc(list):Result.fail();
    }

    //新增(用户)
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        try {
            if (StringUtils.isBlank(user.getNo())) {
                return Result.fail("账号不能为空");
            }
            if (StringUtils.isBlank(user.getPassword())) {
                return Result.fail("密码不能为空");
            }

            user.setPassword(user.getPassword());
            user.setRoleId(2); // 默认角色为普通用户
            boolean saved = userService.save(user);
            return saved ? Result.suc() : Result.fail("注册失败");
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈
            return Result.fail("注册失败: " + e.getMessage());
        }
    }

    //新增(后台)
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        return userService.save(user)?Result.suc():Result.fail();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        if (StringUtils.isBlank(user.getPassword())) {
            User dbUser = userService.getById(user.getId());
            user.setPassword(dbUser.getPassword());
        }
        return userService.updateById(user)?Result.suc():Result.fail();
    }

    //修改
    @PostMapping("/mod")
    public boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }
    //删除
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return userService.removeById(id)?Result.suc():Result.fail();
    }

    //新增或修改
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }

    //删除
    @GetMapping("/delete")
    public boolean delete(Integer id){
        return userService.removeById(id);
    }

    //查询(模糊、匹配)
    @PostMapping("/listP")
    public Result listP(@RequestBody User user) {
         LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
         if (StringUtils.isNotBlank(user.getName())){
             lambdaQueryWrapper.like(User::getName,user.getName());
         }
        return Result.suc(userService.list(lambdaQueryWrapper));
    }

    //入参的封装
    @PostMapping("/listPage")
    public List<User> listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name===>"+(String)param.get("name"));
       /* LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        *//*lambdaQueryWrapper.like(User::getName,user.getName());*//*
        lambdaQueryWrapper.like(User::getNo,user.getNo());
        return userService.list(lambdaQueryWrapper);*/

        /*System.out.println(Query);
        System.out.println("num===>"+Query.getPageNum());
        System.out.println("size===>"+Query.getPageSize());

        HashMap param = Query.getParam();
        System.out.println("name===>"+(String)param.get("name"));
        System.out.println("no===>"+(String)param.get("no"));*/

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

         LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
         lambdaQueryWrapper.like(User::getName,name);

         IPage result = userService.page(page,lambdaQueryWrapper);
         System.out.println("total=="+result.getTotal());
         return  result.getRecords();


    }

    //编写分页mapper方法(Custom)
    @PostMapping("/listPageC")
    public List<User> listPageC(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name===>"+(String)param.get("name"));


        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        /*IPage result = userService.pageC(page);*/
        IPage result = userService.pageCC(page,lambdaQueryWrapper);
        System.out.println("total=="+result.getTotal());
        return  result.getRecords();


    }
    //头像获取接口
    @GetMapping("/avatar/{id}")
    public void getAvatar(@PathVariable String id, HttpServletResponse response)throws IOException {
        User user = userService.getById(id);
        if (user == null || user.getAvatarBytes() == null) {
            response.sendError(404, "Avatar not found");
            return;
        }
        String contentType = user.getAvatarType();
        response.setContentType(contentType != null ? contentType : "image/jpeg");
        response.getOutputStream().write(user.getAvatarBytes());

    }
    //头像上传接口
    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file,
                               @RequestParam String userId)
            throws IOException{
        if (file.isEmpty()) {
            return Result.fail();
        }
        if (!Arrays.asList("image/jpeg", "image/png").contains(file.getContentType())) {
            return Result.fail();
        }
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.fail();
        }
        User user = userService.getById(userId);
        if (user == null) {
            return Result.fail();
        }
        //直接存储二进制数据，文件类型
        user.setAvatarType(file.getContentType());
        user.setAvatarBytes(file.getBytes());
        //更新用户数据
        return userService.updateById(user) ? Result.suc() : Result.fail();
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestParam String no, @RequestParam String newPassword) {
        User user = userService.lambdaQuery().eq(User::getNo, no).one();
        if (user == null) {
            return Result.fail("用户不存在");
        }
        user.setPassword(newPassword);
        userService.updateById(user);
        return Result.suc("密码重置成功");
    }

    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8"); // 关键设置
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        Integer roleId = null;
        try {
            String roleIdStr = (String) param.get("roleId");
            if (roleIdStr != null && !roleIdStr.isEmpty()) {
                roleId = Integer.parseInt(roleIdStr); // 字符串转整数
            }
        } catch (NumberFormatException e) {
            // 处理非法参数（例如非数字字符串）
            return Result.fail("roleId 参数格式错误");
        }

        Page<User> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (roleId != null) {
            lambdaQueryWrapper.eq(User::getRoleId, roleId); // 精确匹配 roleId
        }
        if (StringUtils.isNotBlank(name) && !"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        IPage<User> result = userService.pageCC(page,lambdaQueryWrapper);
        List<User> records = result.getRecords();
        System.out.println("total=="+result.getTotal());
        return  Result.suc(result.getRecords(),result.getTotal());
    }

}
